<template>
  <div>
    <el-form
      ref="formRef"
      :model="loginForm"
      label-width="120px"
      class="demo-dynamic"
      :rules="rules"
    >
      <el-form-item prop="username" label="账号">
        <el-input v-model="loginForm.username" />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="loginForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import type { FormRules, FormInstance } from "element-plus";
import {userlogin} from '@/request/api'
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
const route = useRouter()
const store = useStore()

const formRef = ref<FormInstance>();

// 双向数据绑定的值
let loginForm = reactive({
  username: "",
  password: "",
});

let rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 8, message: "长度应该为2-8个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 10, message: "长度应该为3-10个字符", trigger: "blur" },
  ],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async(valid) => {
    if (valid) {
      // console.log("submit!");
      let res = await userlogin(loginForm)
      // console.log(res);
      store.dispatch("changeUserInfo", res.list);
      ElMessage.success(res.msg);
      route.push('/index')
    } else {
      console.log(valid,"登录失败");
      // return false;
    }
  });
};
</script>

<style lang="less" scoped>
div {
  .demo-dynamic {
    width: 500px;
    height: 300px;
    // background: #ccc;
    position: absolute;
    left: 400px;
    top: 250px;
  }
}
</style>
